package gridModel;

import globalTools.Languages;

import java.awt.Point;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;

public abstract class StdGridModel implements GridModel, Serializable {
	
	// ATTRIBUTS
	
	private static final long serialVersionUID = 1L;
	
	protected Map<Languages, String> name;
	protected Map<NamedColor, PixGrid> playableGrids;
	protected NamedColor actualColor;
	protected PropertyChangeSupport listeners;
	
	protected String file;
	
	// CONSTRUCTEUR
	
	public StdGridModel(Map<Languages, String> names) {
		name = names;
	}
	
	// REQUETES
	
	@Override
	public String getFileName() {
		return file;
	}
	
	@Override
	public String getName(Languages l) {
		return name.get(l);
	}
	
	@Override
	public Map<Languages, String> getNames() {
		return name;
	}

	@Override
	public int getWidth() {
		return playableGrids.get(actualColor).getWidth();
	}

	@Override
	public int getHeight() {
		return playableGrids.get(actualColor).getHeight();
	}

	@Override
	public Set<NamedColor> getColors() {
		return playableGrids.keySet();
	}

	@Override
	public NamedColor getActualColor() {
		return actualColor;
	}

	@Override
	public NamedColor thereIs(int x, int y, PixStates state) {
		for (NamedColor c : playableGrids.keySet()) {
			if (playableGrids.get(c).getPixState(x, y).equals(state)) {
				return c;
			}
		}
		return null;
	}

	@Override
	public PixStates getPixState(int x, int y) {
		return playableGrids.get(actualColor).getPixState(x, y);
	}

	@Override
	public PropertyChangeListener[] getPropertyChangeListeners() {
		if (listeners == null) {
			return null;
		}
		return listeners.getPropertyChangeListeners();
	}
	
	// COMMANDES

	@Override
	public void setPixState(int x, int y, PixStates state) {
		if (!state.equals(PixStates.FULL) || thereIs(x, y, state) == null) {
			playableGrids.get(actualColor).setPixState(x, y, state);
			if (listeners != null) {
				listeners.firePropertyChange("pix", new Point(x, y), state);
			}
		}
	}

	@Override
	public void setActualColor(NamedColor c) {
		NamedColor oldValue = actualColor;
		actualColor = c;
		if (listeners != null) {
			listeners.firePropertyChange("actualColor", oldValue, c);
		}
	}

	@Override
	public void addPropertyChangeListener(PropertyChangeListener l) {
		if (l == null) {
			throw new IllegalArgumentException();
		}
		if (listeners == null) {
			listeners = new PropertyChangeSupport(this);
		}
		listeners.addPropertyChangeListener(l);
	}

	@Override
	public void removePropertyChangeListener(PropertyChangeListener l) {
		if (l == null) {
			throw new IllegalArgumentException();
		}
		listeners.removePropertyChangeListener(l);
	}

}
